<template>
    <div>
        <div>
            <el-breadcrumb separator-class="el-icon-arrow-right" style="height: 30px;">
                <el-breadcrumb-item>HR系统</el-breadcrumb-item>
                <el-breadcrumb-item>信息管理</el-breadcrumb-item>
                <el-breadcrumb-item>部门管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <!-- 搜索 -->
        <div>
            <el-form label-width="100px" style="flex: 1;">
                <div style="display: flex;">
                    <el-row>
                        <el-col style="width: 100px;">
                            <el-form-item label="部门编码："></el-form-item>
                        </el-col>
                        <el-col style="width: 200px;">
                            <el-input placeholder="请输入部门编码：" v-model="queryInfo.code"></el-input>
                        </el-col>
                        <el-col style="width: 100px;">
                            <el-form-item label="部门名称："></el-form-item>
                        </el-col>
                        <el-col style="width: 200px;">
                            <el-input placeholder="请输入部门名称：" v-model="queryInfo.name"></el-input>
                        </el-col>
                        <el-col style="width: 100px;margin-left: 20px;">
                            <el-form>
                                <el-form-item>
                                    <el-button type="primary" @click="getDepartmentData()" size="mini"
                                        style="height: 40px;"><i class="el-icon-search" />搜索</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                        <el-col style="width: 100px;">
                            <el-button type="danger" @click="reset()" size="mini" style="height: 40px;">重置 <i
                                    class="el-icon-refresh-left" /></el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-form>
        </div>
        <div class="button-container">
            <el-button type="primary" plain @click="addDialogVisible = true"
                icon="el-icon-plus">新增</el-button><!--当添加部门时，弹框出现 -->
            <el-button type="primary" plain icon="el-icon-delete" @click="batchDeleteDept()">批量删除</el-button>
            <el-button type="primary" plain class="iconfont icon-hrjiesuo" @click="batchShengXiaoDept()">生效</el-button>
            <el-button type="primary" plain class="iconfont icon-hrsuoding" @click="batchShiXiaoDept()">失效</el-button>
        </div>

        <!-- 查询出来的结果区域 -->
        <div class="common-table">
            <el-table ref="departTable" :data="departMentList" height="350px" border stripe :header-cell-style="{
                                background: '#eef1f6', color: '#606266',
                                textAlign: 'center', fontWeight: 'bold', borderWidth: '3px'
                            }" @selection-change="handleSelectionChange">
                <el-table-column type="selection"></el-table-column>
                <el-table-column label="部门id" align="center" prop="id"></el-table-column>
                <el-table-column label="部门编码" align="center" prop="code"></el-table-column>
                <el-table-column label="部门名称" align="center" prop="name"></el-table-column>
                <el-table-column label="上级部门" align="center" prop="pname"></el-table-column>
                <el-table-column label="所属区域" align="center" prop="area"></el-table-column>
                <el-table-column label="状态" align="center" prop="status">
                    <template slot-scope="scope">
                        <span v-if="scope.row.status == '1'">有效</span>
                        <span v-else-if="scope.row.status == '0'">无效</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="420px" align="center">
                    <template slot-scope="scope">
                        <el-row>
                            <el-col style="width: 80px;">
                                <!-- 修改 -->
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                    @click="EditDept(scope.row.code)" style="width: 70px;">编辑</el-button>
                            </el-col>
                            <el-col style="width: 80px;">
                                <!-- 删除 -->
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="DeleteDept(scope.row.code)" style="width: 70px;">删除</el-button>
                            </el-col>
                            <el-col style="width: 80px;">
                                <!-- 生效 -->
                                <el-button type="success" class="iconfont icon-hrjiesuo" size="mini"
                                    @click="deptStateShengXiao(scope.row.code, scope.row.status)"
                                    style="width: 70px;">生效</el-button>
                            </el-col>
                            <el-col style="width: 80px;">
                                <!-- 失效 -->
                                <el-button type="info" class="iconfont icon-hrsuoding" size="mini"
                                    @click="deptStateShiXiAo(scope.row.code, scope.row.status)"
                                    style="width: 70px;">失效</el-button>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页组件 size-change 每页最大变化 current-change 当前最大变化 layout功能组件-->
        <div class="pager">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNumber" :page-sizes="[5, 10, 20, 50]" :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <!-- 添加部门区域 -->
        <el-dialog title="添加部门" :visible.sync="addDialogVisible" width="50%">
            <el-form :model="addDeptForm" :rules="addDeptFormRules" ref="addDeptFormRef">
                <el-row>
                    <el-col style="width: 120px;">
                        <!-- 部门编码 -->
                        <el-form-item label="部门编码：" prop="code"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <el-input v-model="addDeptForm.code" placeholder="请输入部门编码"></el-input>
                    </el-col>
                    <el-col style="width: 120px;margin-left: 20px;">
                        <!-- 部门名称 -->
                        <el-form-item label="部门名称：" prop="name"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <el-input v-model="addDeptForm.name" placeholder="请输入部门名称"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col style="width: 120px;">
                        <!-- 上级部门编码 -->
                        <el-form-item label="上级部门编码：" prop="pcode"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <!-- <el-input v-model="addDeptForm.pcode" placeholder="请输入上级部门编码"></el-input> -->
                        <el-select v-model="addDeptForm.pcode" :reserve-keyword="false"
                            :remote-method="(a) => { SearchPCode(a) }" :loading="selectLoading"
                            filterable remote value-key="id" clearable style="width: 100%;">
                            <el-option v-for="item in departMentList" :key="`a${item.id}`" :label="`${item.code}`"
                                :value="item.code" />
                        </el-select>
                    </el-col>
                    <el-col style="width: 120px;margin-left: 20px;">
                        <!-- 上级部门 -->
                        <el-form-item label="上级部门名称：" prop="pname"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <el-input v-model="addDeptForm.pname" placeholder="请输入上级部门名称"></el-input>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col style="width: 120px;">
                        <!-- 所属地区 -->
                        <el-form-item label="所属地区：" prop="area"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <el-input v-model="addDeptForm.area" placeholder="请输入所属区域"></el-input>
                    </el-col>
                    <el-col style="width: 120px;margin-left: 20px;">
                        <!-- 部门类型 -->
                        <el-form-item label="部门类型：" prop="deptType"></el-form-item>
                    </el-col>
                    <el-col style="width: 180px;">
                        <el-input v-model="addDeptForm.deptType" placeholder="请输入部门类型"></el-input>
                    </el-col>
                </el-row>
            </el-form>
            <div class="row-container">
                <el-row>
                    <el-col style="width: 100px;">
                        <!-- 取消即关闭窗口 -->
                        <el-button @click="addClose()">取消</el-button>
                    </el-col>
                    <el-col style="width: 100px;">
                        <el-button type="primary" @click="addDept">确定</el-button>
                    </el-col>
                    <el-col style="width: 100px;">
                        <el-button type="info" @click="addDeptClear()">重置</el-button>
                    </el-col>
                </el-row>
            </div>

        </el-dialog>

        <!-- 编辑部门区域 -->
        <el-dialog title="修改部门" :visible.sync="editDialogVisible" width="50%" class="">
            <el-form :model="editDeptForm" :rules="editDeptFormRules" ref="editDeptFormRef">
                <!-- 部门编码 -->
                <el-form-item label="部门编码：" prop="code">
                    <el-input v-model="editDeptForm.code"></el-input>
                </el-form-item>
                <!-- 部门名称 -->
                <el-form-item label="部门名称：" prop="name">
                    <el-input v-model="editDeptForm.name"></el-input>
                </el-form-item>
                <!-- 上级部门 -->
                <el-form-item label="上级部门：" prop="pname">
                    <el-input v-model="editDeptForm.pname"></el-input>
                </el-form-item>
                <!-- 所属地区 -->
                <el-form-item label="所属地区：" prop="area">
                    <el-input v-model="editDeptForm.area"></el-input>
                </el-form-item>
            </el-form>
            <el-row>
                <el-col style="width: 100px;">
                    <!-- 取消即关闭窗口 -->
                    <el-button @click="editClose()">取消</el-button>
                </el-col>
                <el-col style="width: 100px;">
                    <el-button type="primary" @click="editDeptInfo">确定</el-button>
                </el-col>
                <el-col style="width: 100px;">
                    <el-button type="info" @click="editDeptClear()">重置</el-button>
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
export default {
    created() {
        this.getDepartmentData();
    },
    data() {
        return {
            // 查询部门的参数信息
            queryInfo: {
                code: "",//部门code参数
                name: "",//部门名称
                pageNumber: 1,//默认显示的页数
                pageSize: 5,//每页默认显示的数据
            },
            departMentList: [],
            total: 0,//总记录数
            addDialogVisible: false,//对话框默认关闭状态
            // 添加部门的数据
            addDeptForm: {
                code: '',//部门编码
                name: '',//部门名称
                area: '',//所属地区
                pcode: '',//上级部门编码
                pname: '',//上级部门名称
                deptType: ''//部门类型
            },
            selectLoading: false,
            // 编辑部门的数据
            editDeptForm: {
                code: '',//部门编码
                name: '',//部门名称
                area: '',//所属地区
                pname: ''//上级部门
            },
            //显示/隐藏修改部门栏
            editDialogVisible: false,
            //添加部门字段验证
            addDeptFormRules: {
                code: [
                    { required: true, message: '请输入部门编号', trigger: 'blur' },
                    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入部门名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ]
            },

            //编辑部门字段验证
            editDeptFormRules: {
                code: [
                    { required: true, message: '请输入部门编号', trigger: 'blur' },
                    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
                ],
                name: [
                    { required: true, message: '请输入部门名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ]
            },
            //定义一个部门数据数组(即复选框选中的数据)
            deptCodes: [],
        }
    },
    methods: {
        //查询部门的接口
        async getDepartmentData() {
            const { data: res } = await this.$http.get("department", { params: this.queryInfo });
            this.departMentList = res.data.data;
            this.total = res.data.deptCounts;
            if (res.code == 113) {
                return this.$message.error(res.message);
            }
        },

        //监听 page size 改变的事件
        handleSizeChange(newSize) {
            this.queryInfo.pageSize = newSize;
            this.getDepartmentData();
        },
        //监听 页码值 改变的事件
        handleCurrentChange(newPage) {
            this.queryInfo.pageNum = newPage;
            this.getDepartmentData();
        },
        //addDeptClear()方法，当鼠标放在输入框中，清空输入框内容,通过@blur去触发---新增部门信息重置
        addDeptClear() {
            this.addDeptForm.code = '';
            this.addDeptForm.name = '';
            this.addDeptForm.pname = '';
            this.addDeptForm.area = '';
        },
        //editDeptClear()方法，当鼠标放在输入框中，清空输入框内容,通过@blur去触发---新增部门信息重置
        editDeptClear() {
            this.editDeptForm.code = '';
            this.editDeptForm.name = '';
            this.editDeptForm.pname = '';
            this.editDeptForm.area = '';
        },
        reset() {
            this.queryInfo.code = "",
                this.queryInfo.name = ""
        },
        //新增部门
        addDept() {
            this.$refs.addDeptFormRef.validate(async valid => {
                if (!valid) return;
                const { data: res } = await this.$http.post("addDept", this.addDeptForm);
                if (res.message != '成功') {
                    return this.$message.error("新增失败！！！");
                }
                this.$message.success("新增成功！！！");
                this.addDialogVisible = false;
                this.addDeptForm = {
                    code: '',
                    name: '',
                    pname: '',
                    pcode: '',
                    area: ''
                };
                this.getDepartmentData();
            });
        },
        //查询上级部门编码
        async SearchPCode(values) {
            if (values.trim() != '') {
                const { data: res } = await this.$http.get("deptPCodeList?code=" + values);
                this.departMentList = res.data.data;
                this.total = res.data.deptCounts;
                if (res.code == 113) {
                    return this.$message.error(res.message);
                }
            }

        },
        addClose() {
            //清空表单方法
            this.title = '新增窗体'
            this.addDialogVisible = false;
            this.addDeptForm = {
                code: '',
                name: '',
                pname: '',
                area: ''
            };
        },
        //编辑部门对话框
        async EditDept(code) {
            const { data: res } = await this.$http.get("getEditDepartment?code=" + code);//通过部门id去查询需要编辑的部门信息
            this.editDeptForm = res;//查询部门信息反馈到表单里
            this.editDialogVisible = true;//开启编辑对话框
        },
        //编辑窗口关闭
        editClose() {
            this.title = '编辑窗体'
            this.editDialogVisible = false;
        },
        //确认修改
        editDeptInfo() {
            this.$refs.editDeptFormRef.validate(async valid => {
                if (!valid) return;
                //发起修改请求
                const { data: res } = await this.$http.put("editDepartment", this.editDeptForm)
                if (res.message != "成功") {
                    return this.$message.error("修改失败！");
                }
                this.$message.success("修改成功！");
                this.getDepartmentData();
                //隐藏
                return this.editDialogVisible = false;
            })
        },
        // 根据部门code删除部门
        async DeleteDept(code) {
            const confirmResult = await this.$confirm('此操作将永久删除部门，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmResult != 'confirm') {//取消
                return this.$message.info("已取消删除")
            }
            const { data: res } = await this.$http.delete("deleteDepartment?code=" + code);
            if (res.code != 200) {
                return this.$message.error("删除失败！");
            }
            this.$message.success("删除成功！");
            this.getDepartmentData();
        },
        //遍历部门id

        handleSelectionChange() {
            //打印出来的数据 就是勾选获取的勾选那一行的数据
            //console.log(this.$refs.departTable.selection);
            /// 遍历了 勾选获取的那一行数据 然后 赋值给我自己定义的deptCodes这个数组了
            this.deptCodes = this.$refs.departTable.selection.map((item) => item.code);
            // deptCodes 这个数组 就是由勾选每一行的id组成的数组了 这个数组里全是勾选那行的id
            //console.log(this.deptCodes, 777);
        },

        //根据部门ids删除部门(批量删除的方法)
        async batchDeleteDept() {

            const confirmResult = await this.$confirm('此操作将永久删除部门，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if (confirmResult != 'confirm') {//取消
                return this.$message.info("已取消删除")
            }
            let deptCodes = [];
            this.$refs.departTable.selection.map((item) => {
                deptCodes.push(item.code);
            });
            console.log("参数为:" + deptCodes);
            const { data: res } = await this.$http.delete("BatchDeleteDept", { data: deptCodes });
            if (res.code != 200) {
                return this.$message.error("删除失败！");
            }
            this.$message.success("删除成功！");
            this.getDepartmentData();
        },

        //生效部门
        async deptStateShengXiao(code, status) {
            var url = "deptStateShengXiao?code=" + code + "&status=" + status;
            const { data: res } = await this.$http.put(url);
            if (res.code == 302) {
                this.$message.success(res.message);
                return this.getDepartmentData();
            }
            if (res.code == 107) {
                return this.$message.error(res.message);
            }
            this.$message.error(res.message);
        },
        //失效部门
        async deptStateShiXiAo(code, status) {
            var url = "deptStateShiXiAo?code=" + code + "&status=" + status;
            const { data: res } = await this.$http.put(url);
            if (res.code == 304) {
                this.$message.success(res.message);
                return this.getDepartmentData();
            }
            this.$message.error(res.message);
        },

        //根据部门code生效部门(批量生效的方法)
        async batchShengXiaoDept() {
            let deptCodes = [];
            this.$refs.departTable.selection.map((item) => {
                deptCodes.push(item.code);
            });
            console.log("参数为:" + deptCodes);
            const { data: res } = await this.$http.put("BatchShengXiaoDept", deptCodes);
            if (res.code == 200) {
                this.$message.success(res.message);
                return this.getDepartmentData();
            }
            if (res.code == 111) {
                return this.$message.error(res.message);
            }
            this.$message.error(res.message);
        },

        //根据部门code失效部门(批量失效的方法)
        async batchShiXiaoDept() {
            let deptCodes = [];
            this.$refs.departTable.selection.map((item) => {
                deptCodes.push(item.code);
            });
            console.log("参数为:" + deptCodes);
            const { data: res } = await this.$http.put("BatchShiXiaoDept", deptCodes);
            if (res.code == 200) {
                this.$message.success(res.message);
                return this.getDepartmentData();
            }
            if (res.code == 112) {
                return this.$message.error(res.message);
            }
            this.$message.error(res.message);
        },
    }
}

</script>

<style lang="less" scoped>
.content-search {
    background: #ffffff;
    height: 10px;
}

.el-table__body-wrapper {
    overflow-y: auto;
}

.button-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;

}

.el-button {
    display: flex;
    justify-content: center; //水平居中
    align-items: center; //垂直居中
    height: 20px;
    width: 80px;
}

.common-table {
    background-color: white;
    position: relative;
    margin-top: 30px;
    height: 380px;

}

.pager {
    position: relative;
    bottom: 20px;
    right: 20px;
    margin-top: 30px;
}

.row-container {
    display: flex;
    justify-content: flex-end;
}
</style>